import { useState, useMemo, useEffect } from "react";

import { Manager } from "~/lib/manager";
import { ManagerContext, PageContext, DisplayModeContext } from "~/contexts";

import Home from "~/pages/Home";
import NewPost from "~/pages/NewPost";
import PostComments from "~/pages/PostComments";

// @ts-ignore
import "@fontsource/jersey-10";
import "./App.css";

export default function App() {
  const [posts, setPosts] = useState<Post[] | null>(null as Post[] | null);
  const manager = useMemo(() => {
    const manager = new Manager();
    manager.init(setPosts);
    return manager;
  }, []);
  const [pageData, setPage] = useState<PageData>({ key: "home" });
  
  // 从localStorage中读取显示模式设置，如果没有则默认为"default"
  const [displayMode, setDisplayMode] = useState<"default" | "compact">(() => {
    const savedMode = localStorage.getItem('displayMode');
    return savedMode === 'compact' ? 'compact' : 'default';
  });

  // 当显示模式改变时，保存到localStorage
  useEffect(() => {
    localStorage.setItem('displayMode', displayMode);
  }, [displayMode]);

  if (!posts) return;

  let page: any = null;
  if (pageData.key === "home") {
    page = useMemo(() => <Home posts={posts} setDisplayMode={setDisplayMode} displayMode={displayMode} />, [posts, displayMode]);
  } else if (pageData.key === "newpost") {
    page = useMemo(() => <NewPost setDisplayMode={setDisplayMode} displayMode={displayMode} />, [displayMode]);
  } else if (pageData.key === "comments") {
    const post = posts.find((p) => pageData.postId === p.id);
    if (post) {
      page = useMemo(() => <PostComments post={post} setDisplayMode={setDisplayMode} displayMode={displayMode} />, [post, displayMode]);
    } else {
      // post deleted, go home
      setPage({ key: "home" });
    }
  }

  return (
    <ManagerContext.Provider value={manager}>
      <PageContext.Provider value={{ pageData, setPage }}>
        <DisplayModeContext.Provider value={displayMode}>
          {page}
        </DisplayModeContext.Provider>
      </PageContext.Provider>
    </ManagerContext.Provider>
  );
}